package com.example.shirospringboot.realm;


import com.example.shirospringboot.pojo.User;
import com.example.shirospringboot.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;

//自定义realm
public class CustomerRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        User user=userService.findByUserName((String)principalCollection.getPrimaryPrincipal());

        if(!CollectionUtils.isEmpty(user.getRoleList())){
            user.getRoleList().forEach(role -> {
                System.out.println(role.getName());
                authorizationInfo.addRole(role.getName());
            });
            authorizationInfo.addStringPermission("user:*:*");
            return authorizationInfo;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //从传过来的token获取用户名
        String prinicipal=(String) authenticationToken.getPrincipal();
        User user=userService.findByName(prinicipal);
        System.out.println(user.toString());
        if(user!=null){
            return new SimpleAuthenticationInfo(prinicipal,user.getPassword(), ByteSource.Util.bytes(user.getSalt()),this.getName());
        }
        return null;
    }
}
